package cn.yuanqiao.activiti.service.impl;

import cn.yuanqiao.activiti.config.MinioConfig;
import cn.yuanqiao.activiti.service.ISysFileService;
import cn.yuanqiao.activiti.utils.FileUploadUtils;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.file.FileUtils;
import cn.yuanqiao.system.domain.SysFile;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Minio 文件存储
 *
 * @author ruoyi
 */
@Service
public class MinioSysFileServiceImpl implements ISysFileService
{
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient client;

    /**
     * Minio文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception
    {
        String fileName = FileUploadUtils.extractFilename(file);
        InputStream inputStream = file.getInputStream();
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .object(fileName)
                .stream(inputStream, file.getSize(), -1)
                .contentType(file.getContentType())
                .build();
        client.putObject(args);
        inputStream.close();
        return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
    }

    @Override
    public R<SysFile> upload(MultipartFile file) {
        try
        {
            // 上传并返回访问地址
            String url = uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            return R.fail(e.getMessage());
        }
    }

    @Override
    public ResponseEntity<Resource> statics(String path) {
        return null;
    }
}
